package mns.modules.input.pingable;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import mns.*;

/**
 * 
 * @author Dan Moore
 *
 */
public class PingableModule implements MNSInputModule {
	
	public String getName() {
		return "Generic Pingable Input Module";
	}

	public String getOptionsFormHTML() {
		return "Host IP Address: <input type=\"text\" name=\"host\" value=\"10.10.10.10\" />";
	}

	public String getDescriptionHTML() {
		// TODO Auto-generated method stub
		return "";
	}
	
	/**
	 * Used to alert someone if a machine is unreachable via ping.
	 */
	public MNSMessage getMessage(UserOptions opts) {
		String host = "";
		UserOption opt;
		int timeOut = 3000; // I recommend 3 seconds at least
		boolean status;
		MNSMessage msg = new MNSMessage();
		
		try {
			opt = opts.getOption("host");
			host = opt.getValue();
		} catch(NullPointerException e) {
			System.err.println("Bad User Options, not getting msg.");
			return null;
		}
		
		try {
			status = InetAddress.getByName(host).isReachable(timeOut);
		} catch (UnknownHostException e) {
			//e.printStackTrace();
			System.err.println("UnknownHostException in PingableModule.getMessage");
			return null;
		} catch (IOException e) {
			//e.printStackTrace();
			System.err.println("IOException in PingableModule.getMessage");
			return null;
		}
		
		if(status) {
			//machine is still reachable, don't alert
			return null;
		} else {
			String msgs = "Host ["+host+"] is down!";
			msg.setLongMessage(msgs);
			msg.setShortMessage(msgs);
			return msg;
		}		
	}

	public NotificationType getType() {
		return NotificationType.ALERT;
	}

}
